'''
Created on 24 apr 2016

@author: Daniel
'''
from constants.constants        import TABLE_SEPARATE_TRAY
from constants.constants        import ICON_NO_IMAGE
from UI.UI_new_tray_dial        import Ui_Dialog_new_tray
from utils.utils                import getIconPathFromExe
from utils.utils                import getIconsDirectory
from utils.utils                import getFileFromSystem
from new_config_dial            import NewConfigDial
from PyQt4                      import QtGui
from PyQt4.QtCore               import Qt
from utils.utils                import launchMessage
from utils.utils                import computePath
import os
import logging
import shutil


class EmptyObject(object):
    def __init__(self):
        self.description = ''
        self.exe_path = ''
        self.icon_path = ''
        self.name = ''
        self.tooltip = ''
        self.enabled = False
        return super(EmptyObject, self).__init__()

class NewTraydial(QtGui.QDialog, Ui_Dialog_new_tray):
    def __init__(self, dbInst, obj=None, startingName=''):
        super(NewTraydial,self).__init__()
        self.setupUi(self)
        if not obj:
            obj = EmptyObject()
        self.dbInst = dbInst
        self.obj = obj
        self.startingName = startingName
        self.setEvents()
        self.initFields()

    def setEvents(self):
        self.pushButton_exe_path.clicked.connect(self.getSetExe)
        self.pushButton_icon_path.clicked.connect(self.getSetIcon)
        self.pushButton_ok.clicked.connect(self.acceptConfig)
        self.pushButton_cancel.clicked.connect(self.rejectConfig)
        self.lineEdit_name.editingFinished.connect(self.verifyAlreadyPresent)

    def verifyAlreadyPresent(self):
        name = str(self.lineEdit_name.text())
        if name == self.startingName:
            return True
        if self.dbInst.search([('name', '=', str(name))], TABLE_SEPARATE_TRAY):
            launchMessage('Name "%s" must be unique, this name is already in use, please change it.' % (name))
            return False
        return True
        
    def initFields(self):
        self.lineEdit_description.setText(self.obj.description)
        self.lineEdit_exe_path.setText(self.obj.exe_path)
        self.lineEdit_icon_path.setText(self.obj.icon_path)
        self.lineEdit_name.setText(self.obj.name)
        self.textEdit_tooltip.setText(self.obj.tooltip)
        if not self.obj.name:
            self.checkBox_enabled.setChecked(True)
        else:
            self.checkBox_enabled.setChecked(self.obj.enabled)
        if self.obj.icon_path:
            self.setIcon(self.obj.icon_path)
        else:
            self.setImageFromPath('')
        
    def setImageFromPath(self, iconPath, exe_file_path=''):
        iconsDir = getIconsDirectory()
        iconDefaultPath = os.path.join(iconsDir, ICON_NO_IMAGE)
        def noImage():
            iconPath = ''

            if os.path.exists(iconDefaultPath):
                iconPath = iconDefaultPath
            else:
                logging.warning('Icons default path: %s not exists'%(iconDefaultPath))
            return iconPath
        if iconPath:
            self.setIcon(iconPath)
            self.lineEdit_icon_path.setText(iconPath)
            return 
        exeExist = os.path.exists(exe_file_path)
        if not exe_file_path or not exeExist:
            iconPath = noImage()
        elif exeExist:
            iconPath = getIconPathFromExe(exe_file_path)
            if not iconPath:
                iconPath = noImage()
        self.setIcon(iconPath)
        self.lineEdit_icon_path.setText(iconPath)

    def setIcon(self, iconPath):
        if iconPath:
            pixmap = QtGui.QPixmap(iconPath)
            self.label_image.setFixedWidth(75)
            self.label_image.setFixedHeight(75)
            labelHeight = self.label_image.height()
            labelWidth = self.label_image.width()
            pixmap = pixmap.scaled(labelWidth, 
                                     labelHeight, 
                                     aspectRatioMode=Qt.IgnoreAspectRatio, 
                                     transformMode=Qt.FastTransformation)
            self.label_image.setPixmap(pixmap)
        
    def getSetExe(self):
        dial = NewConfigDial(parent=self)
        if dial.exec_() == QtGui.QDialog.Accepted:
            customFlag = dial.radioButton_custom.isChecked()
            pathsToAdd = []
            if customFlag:
                pathsToAdd.append(dial.lineEdit_out_path.text())
            else:
                indexes = dial.listWidget.selectedIndexes()
                for index in indexes:
                    pathsToAdd.append(index.data().toString())
            if len(pathsToAdd) > 1:
                msg = 'You can select only one path from that form!!!\n You have selected %s paths:\n'%(len(pathsToAdd))
                for path in pathsToAdd:
                    msg = msg+'- '+unicode(path)+'\n'
                launchMessage(msg,'warning')
                return
            self.lineEdit_exe_path.setText(pathsToAdd[0])
            self.setImageFromPath('', pathsToAdd[0])
            if not self.lineEdit_name.text():
                name = os.path.basename(str(pathsToAdd[0]))
                self.lineEdit_name.setText(name.split('.')[0])
    
    def getSetIcon(self):
        openPath = "/home/"
        fileName = getFileFromSystem("Open Icon path", self.obj.icon_path)
        if not fileName:
            fileName = openPath
        iconsDir = getIconsDirectory()
        newIconPath = computePath(os.path.join(iconsDir, os.path.basename(str(fileName))))
        if os.path.exists(newIconPath):
            if computePath(str(fileName)) != newIconPath:
                shutil.copy(str(fileName), newIconPath)
            self.lineEdit_icon_path.setText(unicode(newIconPath))
            self.setImageFromPath(newIconPath, self.obj.exe_path)
        else:
            launchMessage('Icon at Path "%s" does not exists.' % (newIconPath))

    def acceptConfig(self):
        if not self.verifyAlreadyPresent():
            return
        self.obj.name = str(self.lineEdit_name.text())
        if not self.obj.name:
            launchMessage('Field "Name" is required, please compile that field.')
            return
        self.obj.description = str(self.lineEdit_description.text())
        self.obj.exe_path = str(self.lineEdit_exe_path.text())
        self.obj.icon_path = str(self.lineEdit_icon_path.text())
        self.obj.tooltip = str(self.textEdit_tooltip.toPlainText())
        self.obj.enabled = self.checkBox_enabled.isChecked()
        self.accept()
    
    def rejectConfig(self):
        self.reject()
